const fs = require('fs');
const path = require('path');

// 递归遍历目录
function traverseDirectory(dir) {
  const files = fs.readdirSync(dir);
  for (const file of files) {
    if (['default', 'system'].includes(file)) continue;
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);
    if (stat.isDirectory()) {
      traverseDirectory(filePath);
    } else if (path.extname(filePath) === '.liquid') {
      processLiquidFile(filePath);
    }
  }
}

// 循环替换文本
function replaceTextInFile(filePath, oldText, newText) {
  const content = fs.readFileSync(filePath, 'utf8');
  const newContent = content.replace(new RegExp(/{{(.*?)}}/g), (match, $1) => {
    if (String($1).trim() === oldText) {
      return `{{ ${newText} }}`;
    }
    return match;
  });
  fs.writeFileSync(filePath, newContent, 'utf8');
}

function getContentSrc(vars) {
  let srcs = [];
  for (const el of vars) {
    if (['src','video_src'].includes(el.split('|')[0].trim().split('.').pop())) {
      if (!el.includes('public_front_asset_url')) {
        srcs.push(el);
      }
    }
  }
  return srcs;
}

function getContentTextarea(vars, textEditorIds) {
  let texts = [];
  for (const el of vars) {
    for (const id of textEditorIds) {
      if (el.split('|')[0].trim().split('.').pop() === id) {
        if (!el.includes('html_content_filter')) {
          texts.push(el);
        }
      }
    }
  }
  return texts;
}

function getVariable(content) {
  const variableRegex = /{{(.*?)}}/g;
  let vars = [];
  for (const match of content.matchAll(variableRegex)) {
    vars.push(match[1].trim());
  }
  return vars;
}

// 处理单个 Liquid 文件
function processLiquidFile(filePath) {
  const content = fs.readFileSync(filePath, 'utf8');
  const schemaMatch = content.match(/{% schema %}(.*?){% endschema %}/s);
  let character = [];
  let imgSrc = [];
  if (schemaMatch) {
    const schema = JSON.parse(schemaMatch[1]);
    const textEditorIds = [];
    if (schema.settings) {
      for (const setting of schema.settings) {
        if (setting.type === 'card_text_editor') {
          textEditorIds.push(setting.id);
        }
        if (setting.type === 'card_textarea') {
          textEditorIds.push(setting.id);
        }
      }
    }
    if (schema.blocks) {
      for (const block of schema.blocks) {
        if (block.settings) {
          for (const setting of block.settings) {
            if (
              setting.type === 'card_text_editor' &&
                            !textEditorIds.includes(setting.id)
            ) {
              textEditorIds.push(setting.id);
            }
            if (
              setting.type === 'card_textarea' &&
                            !textEditorIds.includes(setting.id)
            ) {
              textEditorIds.push(setting.id);
            }
          }
        }
      }
    }
    let vars = getVariable(content);
    imgSrc.push(...getContentSrc(vars));
    if (textEditorIds.length > 0) {
      character.push(...getContentTextarea(vars,textEditorIds));
    }
  }
  if (imgSrc.length) {
    console.log(imgSrc, filePath);
    imgSrc.map((item) => {
      replaceTextInFile(filePath, item, item + '|public_front_asset_url');
    });
  }
  if (character.length) {
    console.log(filePath, character);
    // character.map((item) => {
    //     replaceTextInFile(filePath, item, item + "|html_content_filter");
    // });
  }
  return character;
}

// 开始遍历目录
const srcThemeDir = path.join(process.cwd(), 'src', 'theme','system');
traverseDirectory(srcThemeDir);
